<?php
namespace app\wechat\controller;
class Applet
{
    protected function _initialize(){
        $memberid = 2;
        define('MID', $memberid);	//用户账号id，不能叫UID是因为会和登录的用户的UID重复
        define('WID', MID);	 //用户的公众账号id，目前是一个用户一个账号的情况，所以是WID == MID
    }
    public function getopenid()
    {

        define('WID', 2);
        $data = input('post.');
        $config = db(\tname::weixin_config)->where(array('uid' => WID))->find();
        $appid = $config['appid'];
        $secret = $config['appsecret'];
        $js_code = $data['code'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$js_code&grant_type=authorization_code";

        $result = https_request($url);
        apilog(WID, 'wechat', 'getopenid', $url, '', serializeMysql($result));
        $vip = db(\tname::vip)->where(array('uid' => WID, 'openid' => $result['openid']))->find();
        if (empty($vip)) {
            $data = array(
                'uid' => WID,
                'openid' => $result['openid'],
//                'unionid' 		=> $result['unionid'],//批注：2017-09-30小程序和公众号绑定的，必须先进入公众号，小程序才能获取到unionid
                'source' => 2,
                'create_time' => time(),
            );
            db(\tname::vip)->insert($data);
        }
        else{
            $data = array(
                'uid' => WID,
                'openid' => $result['openid'],
//                'unionid' 		=> $result['unionid'],//批注：2017-09-30小程序和公众号绑定的，必须先进入公众号，小程序才能获取到unionid
                'source' => 2,
            );
            db(\tname::vip)->where(array("openid"=>$result['openid']))->update($data);
        }
        return json($result);
    }
    /**
     * 根据openid和vipid判断是否生成新的用户	2016-11-16
     */
    public function checkopenid($userinfo){
        $vip = db(\tname::vip) -> where(array('uid'=>2,'openid'=>$userinfo['openid'])) -> find();
        if(empty($vip)){
            $data = array(
                'uid'	 		=> 2,
                'openid' 		=> $userinfo['openid'],
                //'unionid' 		=> $userinfo['unionid'],
                'headimgurl' 	=> $userinfo['headimgurl'],
                'nickname' 		=> $userinfo['nickname'],
                'subscribe'     => 1,
                'subscribe_time'=>time(),
                'source'		=> 2,
                'create_time'	=> time(),
            );
            $res = db(\tname::vip)->insert($data);
        }else{
            $data0 = array($vip['nickname'],$vip['headimgurl']);
            $data1 = array($userinfo['nickname'],$userinfo['headimgurl']);
            if($data0 != $data1){
                $vipData = array(
                    'nickname'		=> $userinfo['nickname'],
                    'headimgurl'	=> $userinfo['headimgurl'],
                );
                db(\tname::vip) -> where(array('id'=>$vip['id'])) -> update($vipData);
            }
        }
    }

}